
  layui.config({
        base: './../../layui/lay/modules/'
    });
	
layui.use(['form','layer','laydate','table','laytpl','notice'],function(){
    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        laydate = layui.laydate,
        laytpl = layui.laytpl,
				notice=layui.notice,
        table = layui.table;
				


	const bookVue=new Vue({
		el: '#newsList',
		data:{
			all_data:null,
			tableIns:null,
			categorys:{}
		},
		methods:{
			
			initfill:function(){
				table.render({
					elem: '#newsList',
					url:global_url+'/admin/novel/findNovelAll',
					headers:{
		    	"Authorization":window.localStorage.getItem("token"),
		    	"Accept":"application/json, text/plain, */*",
		    	"Content-Type":"application/json;charset=utf-8"
		    }
		    ,request: {
			    pageName: 'pageNum' //页码的参数名称，默认：page
			    ,limitName: 'pageSize' //每页数据量的参数名，默认：limit
			  },
			  response: {
			    statusName: 'code' //规定数据状态的字段名称，默认：code
			    ,statusCode: 1000 //规定成功的状态码，默认：0
			    ,msgName: 'msg' //规定状态信息的字段名称，默认：msg
			    ,countName: 'totalPages' //规定数据总数的字段名称，默认：count
			    ,dataName: 'books' //规定数据列表的字段名称，默认：data
			  },
					cellMinWidth : 95,
					page : true,
					height : "full-125",
					id : "newsListTable",
					cols : [[
						{type: "checkbox", fixed:"left", width:50},
						{field: 'id', title: 'ID', width:60, align:"center"},
						{field: 'novelId', title: '小说ID', width:60, align:"center"},
						{field: 'author', title: '作者', align:"center",templet:function(d){
							return  d.author==null?"不存在": d.author.penName
						}},
						{field: 'novelName', title: '书名',align:'center'},
						{field: 'type', title: '类型',align:'center',templet:function(d){
							 var types=""
							 for(var i=0;i<d.categories.length;i++){
								 types+=d.categories[i].categoryName+","
							 }
							 
							
							return types.substring(0,types.length-1)
						}},
						{field: 'cover', title: '封面地址', align:'center'},
						{field: 'collectionNumber', title: '收藏数', align:'center', width:60},
						{field: 'sentiment', title: '人气', align:'center', width:60},
						{field: 'introduce', title: '简介', width:350, align:'center'},
						{field: 'novelSource', title: '源',  align:'center'},
						{title: '操作', width:170, templet:'#newsListBar',fixed:"right",align:"center"}
					]]
				});
			},
			tablefill:function(){

			
				this.tableIns = table.render({
					elem: '#newsList',
					cellMinWidth : 95,
					page : true,
					height : "full-125",
					id : "newsListTable",
					cols : [[
						{type: "checkbox", fixed:"left", width:50},
						{field: 'id', title: 'ID', width:60, align:"center"},
						{field: 'novelId', title: '小说ID', width:60, align:"center"},
						{field: 'author', title: '作者', align:"center",templet:function(d){
							return  d.author==null?"不存在": d.author.penName
						}},
						{field: 'novelName', title: '书名',align:'center'},
						{field: 'type', title: '类型',align:'center',templet:function(d){
							 var types=""
							 for(var i=0;i<d.categories.length;i++){
								 types+=d.categories[i].categoryName+","
							 }
							 
							
							return types.substring(0,types.length-1)
						}},
						{field: 'cover', title: '封面地址', align:'center'},
						{field: 'collectionNumber', title: '收藏数', align:'center', width:60},
						{field: 'sentiment', title: '人气', align:'center', width:60},
						{field: 'introduce', title: '简介', width:350, align:'center'},
						{field: 'novelSource', title: '源',  align:'center'},
						{title: '操作', width:170, templet:'#newsListBar',fixed:"right",align:"center"}
					]],data:this.all_data
				});
			
			},
			bookList:function(){
//				this.$http.post(global_url+"/admin/novel/findNovelAll")
//					.then(
//					response=>{
//						this.all_data=response.body.datas.books
//						this.tablefill()
//					},					
//					response=>{
//					})
			},
			deletNovel:function(id){
				Vue.http.post(global_url+'/admin/novel/delete/'+id).then(
					response=>{
						//刷新父页面
						bookVue.initfill()
						layer.msg(response.body.msg)
					},
					response=>{
						layer.msg(response.body.msg)
					}
				)
			},
			addOnlineNovel:function(url){
				
				var formData = new FormData();
				formData.append('url', url);
				Vue.http.post(global_url+'/admin/novel/online/add',formData).then(
					response=>{
						notice.init({
							type: "default",
							autoClose: true,
							title: response.body.msg,
							desktop: true,
						});
					},
					response=>{
						notice.init({
							type: "danger",
							autoClose: true,
							title: response.body.msg,
							desktop: true,
						});
					}
				)
			},
			findByName:function(name){
				Vue.http.post(global_url+'/admin/novel/findName/'+name).then(
					response=>{
						this.all_data=response.body.datas
						this.tablefill()
					},
					response=>{
						notice.init({
							type: "danger",
							autoClose: true,
							title: response.body.msg,
							desktop: true,
						});
					}
				)
			},
			addcategorysHtml:function(data){
					var newHtml=''
					for(var i=0;i<this.categorys.length;i++){
						var html='<input type="checkbox" name='+this.categorys[i].categoryName+' lay-skin="primary" title='+this.categorys[i].categoryName+'>'
						
						if(data!=null){
							data.forEach(function(value,j){
								if(bookVue.categorys[i].categoryName==value){
									html='<input type="checkbox" name='+bookVue.categorys[i].categoryName+' lay-skin="primary"  checked  title='+bookVue.categorys[i].categoryName+'>'
								}
							})
						}
						newHtml+=html
					}
					return newHtml;
			}
		}
	})
	
	bookVue.initfill()
//	bookVue.bookList()

// 
//     //新闻列表
//     var tableIns = table.render({
//         elem: '#newsList',
//         url : '../../json/newsList.json',
//         cellMinWidth : 95,
//         page : true,
//         height : "full-125",
//         limit : 20,
//         limits : [10,15,20,25],
//         id : "newsListTable",
//         cols : [[
//             {type: "checkbox", fixed:"left", width:50},
//             {field: 'newsId', title: 'ID', width:60, align:"center"},
//             {field: 'newsName', title: '文章标题', width:350},
//             {field: 'newsAuthor', title: '发布者', align:'center'},
//             {field: 'newsStatus', title: '发布状态',  align:'center',templet:"#newsStatus"},
//             {field: 'newsLook', title: '浏览权限', align:'center'},
//             {field: 'newsTop', title: '是否置顶', align:'center', templet:function(d){
//                 return '<input type="checkbox" name="newsTop" lay-filter="newsTop" lay-skin="switch" lay-text="是|否" '+d.newsTop+'>'
//             }},
//             {field: 'newsTime', title: '发布时间', align:'center', minWidth:110, templet:function(d){
//                 return d.newsTime.substring(0,10);
//             }},
//             {title: '操作', width:170, templet:'#newsListBar',fixed:"right",align:"center"}
//         ]]
//     });



    //是否置顶
    form.on('switch(newsTop)', function(data){
        var index = layer.msg('修改中，请稍候',{icon: 16,time:false,shade:0.8});
        setTimeout(function(){
            layer.close(index);
            if(data.elem.checked){
                layer.msg("置顶成功！");
            }else{
                layer.msg("取消置顶成功！");
            }
        },500);
    })

    //搜索【此功能需要后台配合，所以暂时没有动态效果演示】
    $(".search_btn").on("click",function(){
        if($(".searchVal").val() != ''){
            bookVue.findByName($(".searchVal").val())
        }else{
           bookVue.initfill()
        }
    });

    //小说管理
    function addNews(edit){
			Vue.http.post(global_url+'/admin/novel/categorys/all').then(
					response=>{
						
						var  category=response.body.datas.category;
						
						var index = layui.layer.open({
								title : "小说管理",
								type : 2,
								content : "bookinfo.html",
								success : function(layero, index){
										var body = layui.layer.getChildFrame('body', index);
										if(edit){
												console.log(edit)	
												bookVue.categorys=category;
												var names=[]
												for(var p=0;p<edit.categories.length;p++){
													names[p]=edit.categories[p].categoryName
												}
												var newHtml=bookVue.addcategorysHtml(names);
											
												body.find(".id").val(edit.id);
												body.find(".novelId").val(edit.novelId);
												body.find(".bookName").val(edit.novelName);
												if(edit.author==null){
													body.find(".author").val("不存在");
												}else{
													body.find(".author").val(edit.author.penName);
												}
												
												body.find(".collectionNumber").val(edit.collectionNumber);
												body.find(".sentiment").val(edit.sentiment);
												body.find(".introduce").val(edit.introduce);
												body.find(".cover").val(edit.cover);
												body.find(".thumbImg").attr("src",edit.cover);
												body.find(".pcheckbox").append(newHtml);
											
												form.render(null,"bookinfopage");
										}
										setTimeout(function(){
												layui.layer.tips('点击此处返回文章列表', '.layui-layer-setwin .layui-layer-close', {
														tips: 3
												});
										},500)
								}
						})
						
				
						layui.layer.full(index);
						//改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
						$(window).on("resize",function(){
								layui.layer.full(index);
						})
					},					
					response=>{
						layer.msg(response.body.status)
					})
			
    }
		
		
		//跳转添加小说
		function addBook(edit){
			Vue.http.post(global_url+'/admin/novel/categorys/all').then(
					response=>{
						
						var  category=response.body.datas.category;
						
						var index = layui.layer.open({
								title : "小说管理",
								type : 2,
								content : "addbook.html",
								success : function(layero, index){
										var body = layui.layer.getChildFrame('body', index);
											bookVue.categorys=category;
											
											var newHtml=bookVue.addcategorysHtml(null);
										
											body.find(".pcheckbox").append(newHtml);
										
											form.render(null,"bookinfopage");
										setTimeout(function(){
												layui.layer.tips('点击此处返回文章列表', '.layui-layer-setwin .layui-layer-close', {
														tips: 3
												});
										},500)
								}
						})
						
				
						layui.layer.full(index);
						//改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
						$(window).on("resize",function(){
								layui.layer.full(index);
						})
					},					
					response=>{
						layer.msg(response.body.status)
					})
			
		}
		
		
    $(".addNews_btn").click(function(){
        addBook();
    })
		
		
		
		
		
		
		
		$(".add_online_book_btn").click(function(){
			layer.prompt({title: '请输入小说地址', formType: 3}, function(pass, index){
				bookVue.addOnlineNovel(pass);
				layer.close(index);
			})
		})
		
		
		
		
		
		

    //批量删除
    $(".delAll_btn").click(function(){
        var checkStatus = table.checkStatus('newsListTable'),
            data = checkStatus.data,
            bookId = [];
		
        if(data.length > 0) {
           
            layer.confirm('确定删除选中的小说？', {icon: 3, title: '提示信息'}, function (index) {
			   for (var i in data) {
					bookVue.deletNovel(data[i].id)
				}
				
				tableIns.reload();
				layer.close(index);
            })
        }else{
            layer.msg("请选择需要删除的小说");
        }
    })

    //列表操作
    table.on('tool(newsList)', function(obj){
        var layEvent = obj.event,
            data = obj.data;

        if(layEvent === 'edit'){ //编辑
            addNews(data);
        } else if(layEvent === 'del'){ //删除
            layer.confirm('确定删除改小说？',{icon:3, title:'提示信息'},function(index){
				
				bookVue.deletNovel(data.id)
				layer.close(index);


            });
        } else if(layEvent === 'look'){ //预览
            layer.alert("此功能需要前台展示，实际开发中传入对应的必要参数进行文章内容页面访问")
        }
    });

})